package com.ease.framework.figures
{
	import flash.display.Graphics;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	public class Polyline
	{
		private var points:Array;
		public var lineWidth:int=1;

		public function Polyline()
		{
		}

		public function setPoints(ps:Array):void
		{
			points=ps;
		}

		public function drawLine(g:Graphics):void
		{

			var length:int=points.length;
			var i:int=0;
			for (i=0; i < length - 1; i++)
			{
				var start:Point=points[i];
				var end:Point=points[(i + 1)];
				g.moveTo(start.x, start.y);
				g.lineTo(end.x, end.y);
			}

		}

		/**
		 * 判断节点是否在某连接线上.
		 * @param x1
		 * @param y1
		 * @param x2
		 * @param y2
		 * @param px
		 * @param py
		 * @param tolerance
		 * @return
		 *
		 */
		public static function lineContainsPoint(x1:Number, y1:Number, x2:Number, y2:Number, px:Number, py:Number, tolerance:Number):Boolean
		{

			var rect:Rectangle=new Rectangle(x1, y1, x2 - x1, y2 - y1);
			if (!rect.contains(px, py))
				return false;

			var v1x:Number, v1y:Number, v2x:Number, v2y:Number;
			var numerator:int, denominator:int;
			var result:Number=0;

			/**
			 * calculates the length squared of the cross product of two vectors, v1 & v2.
			 */
			if (x1 != x2 && y1 != y2)
			{
				v1x=x2 - x1;
				v1y=y2 - y1;
				v2x=px - x1;
				v2y=py - y1;

				numerator=v2x * v1y - v1x * v2y;

				denominator=v1x * v1x + v1y * v1y;

				result=Number(numerator * numerator / denominator);
			}
			return result <= tolerance * tolerance;
			;

		}

	}
}
